package com.ecode.ecny.service;

import com.ecode.ecny.base.RspHead;
import com.ecode.ecny.base.TxnStatus;
import com.ecode.ecny.dto.convert.ConvertInRspDTO;
import com.ecode.ecny.flow.FlowChain;
import com.ecode.ecny.flow.FlowContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @ClassName ConvertInService
 * @Author mjlft
 * @Date 2021/8/14 16:23
 * @Version 1.0
 * @Description 兑回交易服务
 */
@Service
public class ConvertInService implements TrxFlowService {
    Logger logger = LoggerFactory.getLogger(ConvertInService.class);
    public final static String CONVERT_IN_FLOW = "convertInService";

    @Override
    public void doFlow(FlowContent content) {
        //初始化流程任务
        FlowChain flowChain = FlowChain.init(this::init, "兑回初始化");

        //添加流程
        flowChain.addNext(this::check, "兑回校验")
                .addNext(this::process, "兑回任务处理")
                .addNext(this::response, "兑回结果处理");

        //开始执行流程
        flowChain.doFlow(content, this::errorHandler);
    }

    void init(FlowContent flowContent) {
        logger.info("初始化");
    }

    /**
     * 任务校验
     *
     * @param content
     */
    private void check(FlowContent content) {
        logger.info("任务校验");
    }

    /**
     * 任务处理
     *
     * @param content
     */
    private void process(FlowContent content) {
        logger.info("交易处理");
    }

    /**
     * 响应寄送
     *
     * @param content
     */
    private void response(FlowContent content) {
        createPackage(content, TxnStatus.SUCC, null);
    }

    /**
     * 错误处理
     *
     * @param content
     */
    private void errorHandler(FlowContent content, Exception ex) {
        logger.info("异常处理");
    }

    /**
     * 生成响应报文
     *
     * @param content
     */
    private void createPackage(FlowContent content, String status, Exception ex) {
        ConvertInRspDTO rspDTO = null;
        if (TxnStatus.SUCC.equals(status)) {
            rspDTO = new ConvertInRspDTO();
            rspDTO.setAmount("1000");
        }

        RspHead head = RspHead.createHead(ex);
        content.instanceRsp(rspDTO, head);
    }
}
